package com.example.controller;

import com.example.common.R;
import com.example.domain.Dish;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 下载图片至浏览器，即预览
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void previewImage(String name, HttpServletResponse response) {
        try {
            //String path = Dish.class.getResource("../../../static/imgStore").getPath();

            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(basePath+"/" + name));
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] b=new byte[1024];
            int x=0;
            while ((x=bufferedInputStream.read(b))!=-1){
                outputStream.write(b,0,x);
            }

            bufferedInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //随机文件名
        String fileName = UUID.randomUUID().toString();

        String originalFilename = file.getOriginalFilename();
        //文件后缀，包括.，比如.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileOriginalName = fileName + suffix;

        //存储完整路径
        //String path = Dish.class.getResource("../../../static/imgStore").getPath()+"/"+fileOriginalName;

        try {
            file.transferTo(new File(basePath+"/"+fileOriginalName));
            return R.success(fileOriginalName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("图片上传发生错误，请重新尝试");
        }
    }
}
